﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Sapphire.Linq.Framework
{
    public abstract class Query<T> : IOrderedQueryable<T>
    {
        protected Query(IQueryProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("Provider");
            }
            Provider = provider;
            Expression = Expression.Constant(this);
        }

        protected Query(IQueryProvider provider, Type staticType)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("Provider");
            }
            Provider = provider;
            Expression = staticType != null ? Expression.Constant(this, staticType) : Expression.Constant(this);
        }

        protected Query(IQueryProvider provider, Expression expression)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("Provider");
            }
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }
            if (!typeof(IQueryable<T>).IsAssignableFrom(expression.Type))
            {
                throw new ArgumentOutOfRangeException("expression");
            }
            Provider = provider;
            Expression = expression;
        }

        public Expression Expression { get; protected set; }

        public Type ElementType
        {
            get { return typeof(T); }
        }

        public IQueryProvider Provider { get; protected set; }

        public abstract IEnumerator<T> GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }

        public override string ToString()
        {
            if (Expression.NodeType == ExpressionType.Constant &&
                ((ConstantExpression)Expression).Value == this)
            {
                return "Query(" + typeof(T) + ")";
            }

            return Expression.ToString();
        }
    }
}